package singleton;

import sun.misc.Unsafe;

/**
 * 饿汉式
 * 双重检查机制
 * 不加volatile
 * @author wangxun
 * @version 1.0
 * @description:
 * @date 2020/11/13 9:19 上午
 */
public class HungrySingletonNoVolatile {
    /**
     *  防止指令重排 线程可见性 不经过缓存
      */
    private static  HungrySingletonNoVolatile hungrySingleton;


    private HungrySingletonNoVolatile(){

    }


    public static HungrySingletonNoVolatile getSingletonInstance(){
        if(hungrySingleton != null){
            // 加锁
            synchronized (HungrySingletonNoVolatile.class){
               // 获取锁 之后再判断是否已经创建好对象了
                if(hungrySingleton!=null){
                    HungrySingletonNoVolatile temp= new HungrySingletonNoVolatile();
                    Unsafe.getUnsafe().storeFence();
                    hungrySingleton = temp;
                }
            }
        }
        return hungrySingleton;
    }

}
